from flask import render_template, Blueprint,request

from app.models import Goods, Category

# name:是当前这个蓝图的名称，蓝图负责进行接口路径的注册和声明
bp=Blueprint('index',__name__)

# 在蓝图中，给index()函数分配了一个路径，路径的地址就是“/”,http://localhost:5000/
@bp.route("/")
def index():
    # #request.form.get()---》从表单中取值
    # 分页设置
    # http://localhost:5000?page=1
    # 从请求参数中取值---分页参数
    page=request.args.get("page",1,type=int)

    # 取条件参数
    category_id=request.args.get('category',type=int)
    price_max = request.args.get('price_max', type=float)
    condition = request.args.get('condition')


    # 取出商品模型中的query对象
    query=Goods.query

    # 进行多条件分页筛选
    if category_id:
        # 按分类进行查询
        query=query.filter_by(category_id=category_id)
    if price_max:
        # 按最高价筛选
        query=query.filter(Goods.price <= price_max)
    if condition:
        # 按成色筛选
        query=query.filter_by(condition=condition)

    # 获取请求参数
    keyword = request.args.get('keyword')
    if keyword:
        # select * from goods where title like % keyword %
        # query = query.filter(Goods.title.like('%'+keyword+'%'))
        query = query.filter(Goods.title.contains(keyword)|Goods.description.contains(keyword))

    # 执行分页查询
    goods=query.paginate(page=page,per_page=5)

    # select * from goods order by create_time desc | asc
    #goods=Goods.query.order_by(Goods.create_time.desc()).all()

    # 查询商品分类
    categories=Category.query.all()

    # 会自动去“templates”目录下寻找一个名字叫做“index.html”的模板
    return render_template("index.html",goods=goods,categories=categories)